import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Button, Input, Spin, Table, message, InputNumber, Modal, Select, Drawer } from 'antd';
import styles from "./index.less";
import EditQa from '../../KnowledgeManagement/Overview/editQa';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter'

const Search = Input.Search;
const FormItem = Form.Item;

class RecommendedTreatment extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      totala: 0,
      page: 1,
      pageSize: 10,
      similarList: [],
      query1: '', // 搜索的关键词
      minWordCount: '', // 最小字数
      maxWordCount: '', // 最大字数
      minAskCount: '',  // 最小询问次数
      maxAskCount: '',  // 最大询问次数
      order: 'count',   // 排序字段
      sort: 'desc',  //  排序方式，asc：升序，desc：降序,
      dxList: [],
      selectedRowKeys: [],
      selectedRows: [],
      item: [],
      // 关联参数
      logins: false,
      field: 'q',
      query: '',
      pageA: '',
      pageSizeA: '',
      id: '', // 上下文参数
      loginjqr: false,
      zuid: '',
      shutRelevance: false,
      showModel1: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      close: false,
      qaId: "",
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      questiona: '',
      total: 0,
      fromQaSId: '',
      fromQue: '',
      taskResultId: '',
      close: false,
      questions: [],

    };
  }

  componentDidMount() {
    console.log(this.props.location.params)
    if (this.props.location.params == undefined) {
      console.log('111')
    } else {
      const item = this.props.location.params.item
      this.setState({ item, }, () => {
        this.knowledgeQuestionList()
      })
      console.log(item)

    }
  }

  knowledgeQuestionList = () => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    const { item, page, pageSize, query1, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionList',
        payload: {
          id: item.id,
          query: query1,
          order,
          sort,
        },
        callback: res => {
          console.log('问题推荐列表', res);
          if (res.code === 0) {
            if(!res.data.length){
              console.log('111')
              this.setState({query1:'',similarList:[],login: false},()=>{
                // this.knowledgeRecommendQuestionNext()
              })
            }else{
              this.setState({
                taskResultId: res.data[0].id,
                similarList: res.data,
                dxList:[],
                selectedRowKeys:[],
                 selectedRows:[],
                // totala: res.data.total,
                login: false
              })
            }

            // this.drjl('unknown')
          }
        },
      });
    });
  }

  knowledgeQuestionLists = () => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    const { item, page, pageSize, query1, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionList',
        payload: {
          id: item.id,
          query: query1,
          order,
          sort,
        },
        callback: res => {
          console.log('问题推荐列表', res);
          if (res.code === 0) {
            this.setState({
              similarList: res.data,
              dxList:[],
              selectedRowKeys:[],
               selectedRows:[],
              // totala: res.data.total,
              login: false
            })
            // this.drjl('unknown')
          }
        },
      });
    });
  }


  knowledgeRecommendQuestionNext = () => {
    // 知识库智能维护 问题推荐 下一个 knowledgeRecommendQuestionNext
    this.setState({query1:''},()=>{
      this.props.form.setFields({"inputA":""})
      const { dispatch, currentUser } = this.props;
      const { item } = this.state
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionNext',
          payload: {
            order: item.order,
            sort: item.sort,
            taskResultId: item.id,
            index: item.index
          },
          callback: res => {
            console.log('下一个', res);
            if (res.code === 0) {
              // message.success(`${res.msg}`)
              item.id = res.data.id
              item.std = res.data.std
              item.index = res.data.index
              // item.index += 1
              this.setState({
                item,
              }, () => {
                this.knowledgeQuestionList()
              })
            }else{
              this.setState({login:false})
            }
          },
        });
      });
    })
  }

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
    // 使用方法
    // let user  = this.userInfo()
    // console.log(user)
  }

  // 删除回调
  knowledgeQuestionDelete = (ids) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeQuestionDelete',
        payload: {
          ids,
        },
        callback: res => {
          console.log('删除问题库中的问题', res);
          if (res.code === 0) {
            message.success(`${res.msg}`)
            this.setState({
              login: false,
              selectedRowKeys: [],
            }, () => {
              this.knowledgeQuestionList()
            })
          }
        },
      });
    });
  }

  // 引导黑名单回调
  knowledgeQuestionDelete = (ids, url) => {
    const { selectedRows, item } = this.state
    console.log(selectedRows)
    if (selectedRows.length === 0) { message.error('请至少选择一项') } else {
      console.log('忽略')
      const a = []
      selectedRows.map((item, index) => {
        a.push(item.question)
      })
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: url,
          payload: {
            question: a,
            id: item.id
          },
          callback: res => {
            console.log('忽略推荐问题', res);
            if (res.code === 0) {
              message.success(`${res.msg}`)
              this.setState({
                login: false,
                selectedRowKeys: [],
                dxList: [],
                selectedRows: []
              }, () => {
                this.knowledgeQuestionList()
              })
            }
          },
        });
      });
    }

  }

  // 批量删除
  batchDelete = () => {
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgerecommendquestiondelete')
  }

  // 批量移到黑名单
  moveBlacklist = () => { // knowledgeRecommendQuestionBlacklist
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendQuestionBlacklist')
  }

  // 添加到推荐知识点
  tatknowledgePoint = () => { // knowledgeRecommendquestionrecommendQa
    console.log('添加到推荐知识点')
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendquestionrecommendQa')
  }

  // 添加为新知识点
  tbknowledgePoint = () => {
    console.log('添加为新知识点')
    const { dxList } = this.state

    const { selectedRows, item, selectedRowKeys } = this.state
    if (selectedRows.length === 0) { message.error('请至少选择一项') } else {
      console.log(dxList, selectedRows, selectedRowKeys)
      const arr = []
      selectedRows.map((item) => {
        arr.push(item.question.replace(/<.*?>/g,""))
      })
      console.log(arr, this.qaRef);
      // this.formRef.initKnow();
      this.setState({
        questions: arr,
      }, () => {
        console.log('传参', arr)
        this.setState({ close: true })
      })
    }
  }

  onClose = () => {
    const { dxList } = this.state
    this.setState({
      close: false,
      questions: [],
    },()=>{
      if (this.props.location.params == undefined) {
        console.log('111')
      } else {
        const item = this.props.location.params.item
        this.setState({ item, }, () => {
          this.knowledgeQuestionList()
        })
        console.log(item)
      }
    });
  };

  // // 关联已有知识点
  // tcknowledgePoint = () => {
  //   console.log('关联已有知识点')
  // }

  // 忽略
  lose = () => { // knowledgeRecommendQuestionignore
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendQuestionignore')
  }


  // 排序
  pXhandleChange = (pagination, filters, sorter, ) => {
    console.log(sorter) // "ascend" 升序 "descend"降序 参数 order  field->dataIndex
    if (sorter.field) { } else {
      console.log('初始')
      this.setState({
        order: 'count',
        sort: 'desc'
      }, () => {
        this.knowledgeQuestionList()
      })
    }
    if (sorter.field === "count") { // 询问次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({
          order: 'count',
          sort: 'asc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({
          order: 'count',
          sort: 'desc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
    }
    if (sorter.field === "accuracy") { // 相似度排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({
          order: 'accuracy',
          sort: 'asc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({
          order: 'accuracy',
          sort: 'desc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
    }

  }

  /*
  * --------------关联页面交互------------------------
  */
  // 关联已有知识点
  tcknowledgePoint = () => {
    console.log()
    this.props.form.setFields({ "businessName": "" })
    const { selectedRows, item } = this.state
    console.log(selectedRows)
    if (selectedRows.length === 0) { message.error('请至少选择一项') } else {
      console.log('忽略')
      const a = []
      selectedRows.map((item, index) => {
        a.push(item.question)
      })
      console.log(a[0])
      this.setState({ question: a[0], query: '' }, () => {
        this.AnswerRelevance(
          this.state.robotId,
          this.state.question,
          this.state.field,
          this.state.query,
          1,
          10)
        this.setState({ showModel1: true, guanlianList: a })
      })
    }

  }



  // 获取关联列表数据
  AnswerRelevance = (robotIds, question, field, query, page, pageSize) => {
    this.setState({
      logins: true
    })
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'knowledgeSmartMaintenance/fakeAnswerRelevanceData',
      payload: { robotId: currentUser.robotId, question, field, query, page, limit: pageSize },
      callback: res => {
        console.log(res)
        const aA = res.suggestList
        const bB = res.qaList
        const aALeng = res.suggestList.length
        const bBLeng = res.qaList.length
        console.log(aALeng + bBLeng)
        const total = [...aA, ...bB]
        total.map((item, index) => {
          item.key = index
        })
        this.setState({
          total2: res.total,
          qaListTable: total,
          logins: false,
          aALeng,
          glLeng: Number(aALeng + bBLeng),
        })
      },
    });
  }

  setClassName = (record, index) => {
    return (index < this.state.aALeng ? styles.red : '')
  }

  handleSubmitComment = (current) => {
    console.log('tcx', current, typeof (current))

    this.AnswerRelevance(
      this.state.robotId,
      this.state.question,
      this.state.field,
      this.state.query,
      current,
      this.state.pageSizetwo
    )
  }

  handleSubmitComments = (a, b) => {
    this.setState({ pageSizetwo: b })
    this.AnswerRelevance(
      this.state.robotId,
      this.state.question,
      this.state.field,
      this.state.query,
      a,
      b
    )
  }

  // 搜索问题
  onFromA = (val) => {
    console.log('fu', val)
    let text;
    if (val === '1') { text = 'q' }
    if (val === '2') { text = 'a' }
    this.setState({ pagetwo: 1, pageSizetwo: 10, field: text })
    setTimeout(() => {
      this.AnswerRelevance(this.state.robotId, this.state.question, this.state.field, this.state.query, this.state.pagetwo, this.state.pageSizetwo)
    })
  }

  // 搜索内容
  onFrom = (val) => {
    console.log('fu', val)
    this.setState({ pagetwo: 1, pageSizetwo: 10, query: val, }, () => {
      if (val === '') {
        this.AnswerRelevance(this.state.robotId, this.state.question, this.state.field, this.state.query, this.state.pagetwo, this.state.pageSizetwo)
      } else {
        this.AnswerRelevance(this.state.robotId, val, this.state.field, this.state.query, this.state.pagetwo, this.state.pageSizetwo)
      }
    })
  }

  // 执行关联
  handleDelete = (items) => {
    console.log('item', items)
    this.setState({ shutRelevance: false })
    const { dispatch, currentUser } = this.props;
    const { guanlianList, item } = this.state
    dispatch({
      type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionRelation',
      payload: { question: guanlianList, id: item.id, qaId: items.sid },
      callback: res => {
        if (res.code === 0) {
          message.success(`${res.msg}`);
          this.setState({ showModel1: false, selectedRowKeys: [], dxList: [], selectedRows: [] })
          this.knowledgeQuestionList()
        }
        console.log('关联异常问', res)
      },
    });
  };

  onRef = (ref) => {
    this.qaRef = ref
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        const a = []
        selectedRows.map((item, index) => {
          a.push(item.id)
        })
        this.setState({ dxList: a, selectedRowKeys, selectedRows })
      },
    };
    const columns = [
      {
        title: '问题',
        width: 'calc(50vw)',
        dataIndex: 'question',
        render(item) {
          return (
            <div  dangerouslySetInnerHTML={{ __html: item }}></div>
          )
        }

      },
      {
        title: '询问次数',
        width: 'calc(25vw)',
        sorter: (a, b) => { },
        dataIndex: 'count',
      },
      {
        title: '相似度',
        dataIndex: 'accuracy',
        sorter: (a, b) => { },
        width: 'calc(25vw)',
      },

    ]
    const columns1 = [
      {
        title: '问题',
        dataIndex: 'question'
      },
      {
        title: '分类',
        dataIndex: 'category'
      },
      {
        title: '操作',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div className={styles.buttongx} onClick={(text) => { this.handleDelete(item) }}>
              {/* <MyIcon  type="icon-bi" /> */}
              <span><Icon size="small" type="link" style={{ marginRight: 5 }} /></span>
              <span>关联</span>
            </div>
          </div>
        }
      },
    ]
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, }} xs={24}>
                <div className={styles.title}>
                  <span>推荐问题处理</span>
                  <BackRouter pathname='/capacity/knowledgeSmartMaintenance/problemRecommendedList'></BackRouter>
                </div>
              </Col>
            </Row>
            <Card
              bordered={false}
            >
              <div style={{ marginBottom: 20 }}>
                <Form layout="inline">
                  <FormItem style={{ marginRight: 80, color: '#01c0f6', fontSize: 18 }} label='推荐到知识点'>
                    {this.state.item.std}
                  </FormItem>
                  <FormItem className='buttonYs'>
                    <Button onClick={this.knowledgeRecommendQuestionNext}>下一个</Button>
                  </FormItem>
                </Form>
              </div>
              <div className={styles.border} />
              <Row>
                <Form style={{ marginBottom: 20 }} layout="inline">
                  <FormItem className='zdyButtonD'>
                    <Button onClick={this.tatknowledgePoint} type='primary'>添加到推荐知识点</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.tbknowledgePoint} type='primary'>添加为新知识点</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.tcknowledgePoint} type='primary'>关联已有知识点</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.lose} type='primary'>忽略</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.batchDelete} type='primary'>删除</Button>
                  </FormItem>
                  <FormItem className='zdyButtonB'>
                    <Button onClick={this.moveBlacklist} type='primary'>移到黑名单</Button>
                  </FormItem>
                  <span style={{ float: "right" }}>
                    <FormItem>
                      {getFieldDecorator('inputA', {
                        initialValue:this.state.query1,
                      })(
                        <Search
                          placeholder="请输入关键词"
                          onSearch={value => {
                            console.log(value)
                            this.setState({
                              query1: value,
                            }, () => {
                              this.knowledgeQuestionLists()
                            })
                          }}
                          style={{ width: 325 }}
                        />
                      )}
                    </FormItem>
                  </span>
                </Form>
                <Spin spinning={this.state.login}>
                  <Table
                  //  className='zdyTable'
                    rowSelection={rowSelection}
                    onChange={this.pXhandleChange}
                    style={{ padding: '20px 0px 20px 0px' }}
                    columns={columns}
                    dataSource={this.state.similarList}// 数据
                    pagination={false}
                  // onChange={this.handleChange}
                  // pagination={{  // 分页
                  //   total: this.state.totala,
                  //   pageSize: this.state.pageSize,  // 显示几条一页
                  //   current: this.state.page, // 当前页
                  //   showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                  //   showQuickJumper: true,
                  //   onChange: this.pageWay,
                  //   onShowSizeChange: this.onShowSizepageWay
                  // }}
                  />
                </Spin>
                <Form layout="inline">
                  <FormItem className='zdyButtonD'>
                    <Button onClick={this.tatknowledgePoint} type='primary'>添加到推荐知识点</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.tbknowledgePoint} type='primary'>添加为新知识点</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.tcknowledgePoint} type='primary'>关联已有知识点</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.lose} type='primary'>忽略</Button>
                  </FormItem>
                  <FormItem className='zdyButtonZ'>
                    <Button onClick={this.batchDelete} type='primary'>删除</Button>
                  </FormItem>
                  <FormItem className='zdyButtonB'>
                    <Button onClick={this.moveBlacklist} type='primary'>移到黑名单</Button>
                  </FormItem>
                </Form>
              </Row>
            </Card>
            {/* 关联组件 */}
            <Modal
              style={{ top: 60 }}
              width="calc( 70vw)"
              className={styles.overa}
              title='添加关联知识点'
              visible={this.state.showModel1}
              footer={null}
              onCancel={() => {
                this.setState({
                  showModel1: false
                })
              }}
              onOk={() => { // 确定方法不开出去
                this.setState({
                  showModel1: false
                })
              }}
            >

              <Form layout="inline" style={{ paddingBottom: 20 }}>
                <FormItem style={{ marginLeft: 20 }}>

                  <Select
                    defaultValue={this.state.numberRadio}
                    style={{ width: 160 }}
                    onChange={this.onFromA}
                  >
                    <Option value='1'>搜索问题</Option>
                    <Option value='2'>搜索答案</Option>
                  </Select>
                </FormItem>
                <FormItem>
                  {getFieldDecorator('businessName', {
                    initialValue: '',
                  })(
                    <Search
                      placeholder="请输入搜索内容"
                      onSearch={value => {
                        this.onFrom(value)
                      }}
                      style={{ width: 320 }}
                    />
                  )}
                </FormItem>
              </Form>
              <Spin spinning={this.state.logins}>
                <Table
                  rowClassName={this.setClassName}
                  className={styles.over}
                  //  bordered
                  columns={columns1}
                  dataSource={this.state.qaListTable}
                  pagination={{  // 分页
                    total: this.state.total2, // 数据总数量
                    pageSize: this.state.glLeng,  // 显示几条一页
                    defaultPageSize: this.state.pagetwo, // 当前页
                    // showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                    showQuickJumper: true,
                    onChange: this.handleSubmitComment,
                    onShowSizeChange: this.handleSubmitComments
                  }}
                />
              </Spin>
            </Modal>
            {/* 添加为新知识点 */}

          </div>
          <Drawer
            title={<FormattedMessage id="app.overView.editQa" />}
            placement="right"
            closable={false}
            onClose={this.onClose}
            visible={this.state.close}
            width={800}
            destroyOnClose
          >
            <EditQa taskResultId={this.state.taskResultId} addType='recommend'  questions={this.state.questions} onClose={this.onClose} />
          </Drawer>
        </PageHeaderWrapper>
      </Suspense>
    );
  }

}


export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(RecommendedTreatment));
